package Demo4;

import java.io.OptionalDataException;
import java.util.*;

public class BinaryTree {
    private TreeNode prev;

    static class TreeNode{
        public char val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(char val){
            this.val=val;
        }
        public TreeNode root;
    }
    //手动创建一棵二叉树
    public TreeNode createTree(){
        TreeNode A= new TreeNode('A');
        TreeNode B= new TreeNode('B');
        TreeNode C= new TreeNode('C');
        TreeNode D= new TreeNode('D');
        TreeNode E= new TreeNode('E');
        TreeNode F= new TreeNode('F');
        TreeNode G= new TreeNode('G');
        TreeNode H= new TreeNode('H');
        A.left=B;
        A.right=C;
        B.left=D;
        D.left=E;
        C.left=F;
        C.right=G;
        return A;
    }
    //前序遍历(根->左->右)
    public void preOrder(TreeNode root){
      if (root==null){
          return;
      }
        System.out.print(root.val+" ");
      preOrder(root.left);
      preOrder(root.right);
    }
    //中序遍历(左->根->右)
    public void inOrder(TreeNode root){
        if (root==null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }
    //后续遍历(左->右->根)
    public void postOrder(TreeNode root){
    if (root==null){
        return;
    }
    postOrder(root.left);
    postOrder(root.right);
        System.out.print(root.val+" ");
    }
    //获取二叉树中节点的个数(遍历的思想)
    public static int count=0;
    public void size(TreeNode root){

        if (root==null){
            return ;
        }
        count++;
        size(root.left);
        size(root.right);
    }
    //子问题思想
    public int nodeSize(TreeNode root){
        if (root==null){
            return 0;
        }
        return nodeSize(root.left)+nodeSize(root.right)+1;
    }
    public static int leafCount=0;
    //获取叶子节点个数(遍历思想)
    public void  getLeafNodeCount(TreeNode root){
        if (root==null){
            return;
        }
        if (root.left==null&&root.right==null){
            leafCount++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }
    public int getLeafNodeCount2(TreeNode root){
        if (root==null){
            return 0;
        }
        if (root.left==null&&root.right==null){
            return 1;
        }
        return  getLeafNodeCount2(root.left)+ getLeafNodeCount2(root.right);
    }
    //获取第k层有几个节点
    public int getKLeafNodeCount(TreeNode root,int k){
        if (root==null){
            return 0;
        }
        if(k==1){
            return 1;
        }

        return getKLeafNodeCount(root.left,k-1)+getKLeafNodeCount(root.right,k-1);
    }
    //获取二叉树的深度
    public int getHeight(TreeNode root){
        if (root==null){
            return 0;
        }
        int leftH=getHeight(root.left);
        int rightH=getHeight(root.right);
        return leftH>rightH? leftH+1:rightH+1;
    }
    //在二叉树中找val值
    public TreeNode find(TreeNode root,char val){
        if (root==null){
            return null;
        }
        if(root.val==val){
            return root;
        }
        TreeNode ret=find(root.left,val);
        if (ret!=null){
            return ret;
        }
        TreeNode ret2=find(root.right,val);
        if (ret2!=null){
            return ret2;
        }
        return null;
    }
    //翻转二叉树
    public TreeNode invertTree (TreeNode root){
        if (root==null){
            return null;
        }
        TreeNode tmp=root.left;
        root.left=root.right;
        root.right=tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
    //判断是否是同一颗二叉树
//    public boolean isSameTree(TreeNode p,TreeNode q){
//        if(p!=null&&q==null||p==null&&q!=null){
//            return false;
//        }
//        if(p==null&&q==null){
//            return true;
//        }
//        if(p.val!=q.val){
//            return false;
//        }
//        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
//    }
    //判断subRoot是不是Root的子树
    public boolean isSubTree(BinaryTree.TreeNode root,BinaryTree.TreeNode subRoot){
        //root为空时
        if (root==null){
            return false;
        }
        //root不为空，判断root与subRoot是否是同一棵树(同一棵树也说明subRoot是root的子树)
        if (isSameTree(root,subRoot)){
            return true;
        }
        //判断subRoot是否是root左子树的子树/右子树的子树
        if (isSubTree(root.left,subRoot) ){
            return true;
        }
        if (isSubTree(root.right,subRoot)) {
            return true;
        }
        return false;
    }
    public boolean isSameTree(TreeNode p,TreeNode q){
        if(p!=null&&q==null||p==null&&q!=null){
            return false;
        }
        if(p==null&&q==null){
            return true;
        }
        if(p.val!=q.val){
            return false;
        }
        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
    }
    //判断一棵树是不是对称二叉树
    public boolean isSymmetric(TreeNode root){
        if (root==null){
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
    //判断root的左子树与右子树是否对称
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
        if (leftTree!=null&&rightTree==null||leftTree==null&&rightTree!=null){
            return false;
        }
        if(leftTree==null&&rightTree==null){
            return true;
        }
        if (leftTree.val!=rightTree.val){
            return false;
        }
        return isSymmetricChild(leftTree.left,rightTree.right)&&isSymmetricChild(leftTree.right,rightTree.left);
    }
    //判断一棵树是不是平衡二叉树
    //时间复杂度为O(N^2)
    public boolean isBlanced(TreeNode root){
        if (root==null){
            return true;
        }
        int leftH=getHeight(root.left);
        int rightH=getHeight(root.right);
        return Math.abs(leftH-rightH)<=1&&isBlanced(root.left)&&isBlanced(root.right);
    }
    //时间复杂度为O(N)
    public boolean isBlanced2(TreeNode root){
        if (root==null){
            return true;
        }
        return getHeight2(root)>=0;
    }
    public int getHeight2(TreeNode root){
        if (root==null){
            return 0;
        }
        int leftH=getHeight2(root.left);
        if (leftH<=0){
            return -1;
        }
        int rightH=getHeight2(root.right);
        if (rightH<=0){
            return -1;
        }
        if (leftH>=0&&rightH>=0&&Math.abs(leftH-rightH)<=1){
            return leftH>rightH? leftH+1:rightH+1;
        }
        else {
            return -1;
        }
    }
 //层序遍历
    public void leafOrder(TreeNode root){
        if (root==null){
            return;
        }
        //创建一个队列
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur=queue.poll();
            System.out.println(cur);
            if (cur.left!=null){
                queue.offer(cur.left);
            }
            if (cur.right!=null){
                queue.offer(cur.right);
            }
        }
    }
    //判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root){
        if (root==null){
            return true;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur=queue.poll();
            if (cur!=null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }
            else {
                break;
            }
        }
        while (!queue.isEmpty()){
           TreeNode cur=queue.poll();
           if(cur!=null){
               return false;
           }
        }
        return true;
    }
 //寻找最近的公共祖先(方法1)
    public TreeNode lowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q){
        //先判断是否为空
        if (root==null){
            return null;
        }
        //不为空时，看此刻的root是否是节点p(q)
        if (root==p||root==q){
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if (left!=null&&right!=null){
            return root;
        }
        else if(left!=null){
            return left;
        }
        else {
            return right;
        }
    }
    //寻找最近的公共祖先(方法2)
    public TreeNode lowestCommonAncestor2(TreeNode root,TreeNode p,TreeNode q){
        if (root==null){
            return null;
        }
        //存root到node节点之间所有节点
        Stack<TreeNode> stackP=new Stack<>();
        Stack<TreeNode> stackQ=new Stack<>();
        getPath(root,p,stackP);
        getPath(root,q,stackQ);
        //求两个栈中各自有多少个节点，要将多的节点pop出去，最终两个栈节点个数相同
        int sizeP= stackP.size();
        int sizeQ=stackQ.size();
        //用size记录下两栈节点的差值
        int size=sizeP-sizeQ;
        if (size>0){
            while (size!=0){
                stackP.pop();
                size--;
            }
        }
        else {
            size=sizeQ-sizeP;
            while (size!=0){
                stackQ.pop();
                size--;
            }
        }
        //走到这说明两栈节点个数是相同的，同时从P栈，Q栈中出节点，直到出到相同节点就返回，这个节点就是最近公共祖先节点
        while (!stackP.isEmpty()&&stackQ.isEmpty()){
            if (stackP.peek().equals(stackQ.peek())){
                return stackP.peek();
            }
            else {
                stackP.pop();
                stackQ.pop();
            }
        }
         return null;
    }
    //找从root到node之间的所有节点(包含root,node),并存储到栈stack中
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack){
        //判断是否为空,为空就说明这条路径上所有的节点都不是我要找的节点，返回false
        if (root==null){
            return false;
        }
        stack.push(root);
        //判断入栈的节点是不是我要找的节点
        if (root==node){
            return true;
        }
        //走到这说明此时的root不是我要找的节点，我需要递归root的左边，右边，去寻找
        boolean flg=getPath(root.left, node, stack);
        if (flg){
            return true;
        }
        flg=getPath(root.right, node, stack);
        if (flg){
            return true;
        }
        //root的左右两边都没找到，说明此时的root就不是我需要的那条路径上的节点，将其出栈
        stack.pop();
        return false;
    }
    //根据先序遍历，中序遍历去创建一棵二叉树
    public int preIndex=0;
    public TreeNode createTree(int[] preOrder,int[] inOrder ){
        return createTreeChild(preOrder,inOrder,0, inOrder.length-1);
    }
    public TreeNode createTreeChild(int[] preOrder,int[] inOrder,int inbegin,int inend){

        //判断inbegin是否大于inend,大于就说明没有子树
        if (inbegin>inend){
            return null;
        }
        //根据先序遍历，先去创建一个根节点
        TreeNode root=new TreeNode((char) preOrder[preIndex]);
        //寻找preOrder[preIndex]在中序遍历数组中的位置
        int rootIndex=find(inOrder,inbegin,inend,preOrder[preIndex]);
        preIndex++;
        //递归左子树，右子树
       root.left= createTreeChild(preOrder,inOrder,inbegin,rootIndex-1);
        root.right= createTreeChild(preOrder,inOrder,rootIndex+1,inend);
        return root;
    }
    public int find(int[] inOrder,int inbegin,int inend,int key){
        for (int i =inbegin; i <=inend ; i++) {
            if (inOrder[i]==key){
                return i;
            }
        }
        return -1;
    }


    //根据后序遍历和中序遍历去创建一颗二叉树
    public int postIndex=0;
    public TreeNode createTree2(int[] postOrder,int[] inOrder ){
        postIndex=postOrder.length-1;
        return createTreeChild2(postOrder,inOrder,0, inOrder.length-1);
    }
    public TreeNode createTreeChild2(int[] postOrder,int[] inOrder,int inbegin,int inend){

        //判断inbegin是否大于inend,大于就说明没有子树
        if (inbegin>inend){
            return null;
        }
        //根据先序遍历，先去创建一个根节点
        TreeNode root=new TreeNode((char) postOrder[postIndex]);
        //寻找preOrder[preIndex]在中序遍历数组中的位置

       int rootIndex = find2(inOrder,inbegin,inend,postOrder[postIndex]);
        preIndex--;
        //递归右子树，左子树

        root.right= createTreeChild(postOrder,inOrder,rootIndex+1,inend);
        root.left= createTreeChild(postOrder,inOrder,inbegin,rootIndex-1);
        return root;
    }
    public int find2(int[] inOrder,int inbegin,int inend,int key){
        for (int i =inbegin; i <=inend ; i++) {
            if (inOrder[i]==key){
                return i;
            }
        }
        return -1;
    }

    //根据二叉树创建字符串
    public String tree2str(TreeNode root){
        //new 一个stringBuilder 去存储我遍历二叉树的值
        StringBuilder stringBuilder=new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }
    public void tree2strChild(TreeNode root,StringBuilder stringBuilder){
        if (root==null){
            return;
        }
        stringBuilder.append(root.val);
        //判段root的左子树和右子树是否为空
        //左子树
        if (root.left!=null){
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }
        else {
            if (root.right==null){
                //root的左树，右树都为空
                return;
            }
            else {
                stringBuilder.append("()");
            }
        }
        //右子树
        if (root.right!=null){
            stringBuilder.append("(");
            tree2strChild(root.right, stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
    //前序遍历递归形式(有返回值)
    public List<Integer> preOrderTraversal(TreeNode root){
        //先new 一个list去存储我前序遍历的结果
        List<Integer> list=new ArrayList<>();
        //判断root是否为空，为空就返回list(因为为空说明list里面并没有被添加元素，list就是null)
        if (root==null){
            return list;
        }
        list.add((int) root.val);
        List<Integer> listLeft=preOrderTraversal(root.left);
        list.addAll(listLeft);
        List<Integer> listRight=preOrderTraversal(root.right);
        list.addAll(listRight);
        return list;
    }
    //前序遍历非递归的形式(有返回值)
    public List<Integer> preOrderTraversalNor(TreeNode root){
        //先new 一个list去存储我前序遍历的结果
        List<Integer> list=new ArrayList<>();
        //判断root是否为空，为空就返回list(因为为空说明list里面并没有被添加元素，list就是null)
        if (root==null){
            return list;
        }
        Stack<TreeNode> stack=new Stack<>();
        TreeNode cur=root;
        TreeNode top=null;
        while (cur!=null||!stack.isEmpty()){
            while (cur!=null){
                stack.push(cur);
                list.add((int) cur.val);
                cur=cur.left;

            }
            top=stack.pop();
            cur=top.right;
        }
        return list;
    }
//中序遍历非递归的形式(有返回值)
public List<Integer> inOrderTraversalNor(TreeNode root){
    //先new 一个list去存储我前序遍历的结果
    List<Integer> list=new ArrayList<>();
    //判断root是否为空，为空就返回list(因为为空说明list里面并没有被添加元素，list就是null)
    if (root==null){
        return list;
    }
    Stack<TreeNode> stack=new Stack<>();
    TreeNode cur=root;
    TreeNode top=null;
    while (cur!=null||!stack.isEmpty()){
        while (cur!=null){
            stack.push(cur);
            cur=cur.left;

        }
        top=stack.pop();
        list.add((int) top.val);
        cur=top.right;
    }
    return list;
}
//后序遍历非递归形式(有返回值)
public List<Integer> postOrderTraversalNor(TreeNode root){
    //先new 一个list去存储我前序遍历的结果
    List<Integer> list=new ArrayList<>();
    //判断root是否为空，为空就返回list(因为为空说明list里面并没有被添加元素，list就是null)
    if (root==null){
        return list;
    }
    Stack<TreeNode> stack=new Stack<>();
    TreeNode cur=root;
    TreeNode top=null;
    while (cur!=null||!stack.isEmpty()){
        while (cur!=null){
            stack.push(cur);
            cur=cur.left;

        }
        top=stack.peek();
        if (top.right==null||top.right==prev){
            stack.pop();
            list.add((int) top.val);
            prev=top;
        }else {
            cur=top.right;
        }
    }
    return list;
}
    }



